function fwd()
	forward(A)
	forward(B)
end

function turn(degrees, port)
	nxt.OutputSetRegulation(port,1,1)

	_,tacho = nxt.OutputGetStatus(port)
	nxt.OutputSetSpeed(port,0x20,nxt.sign(degrees)*50,nxt.abs(degrees))

	repeat
		_,curtacho = nxt.OutputGetStatus(port)
	until 4 > nxt.abs( curtacho - (tacho + degrees) )
	write("turn")
end

function back()
	backward(A)
	backward(B)
end

function left()
	forward(B,25)
	backward(A,25)
end

function right()
	forward(A, 25)
	backward(B, 25)
end

function shtop()
	stop(A)
	stop(B)
end

function avoid(margin)
	if sonarReading(1) < margin then
		local a = 0
		repeat
			if a < 10 then
				right()
				a = a +1
			else
				back()
			end
		until sonarReading(1) > margin
	end
end

function follow_avoid()
			if sonarReading(1) < 150 then
				turn(380, B)
				while sonarReading(2) < 150 do
					fwd()
				end
				turn(380, A)
			end
		
	end
	

function dm()
	repeat
		fwd()
		avoid(30)
	until isPressed(ESCAPE)
end


function toWander()
	a = nxt.random(1000)
	if a > 990 then
		right()
	elseif a < 35 then
		left()
	end
end

function wandering()
	repeat
		fwd()
		avoid(30)
		toWander()
	until isPressed(ESCAPE)
end

function wall()
	repeat
		if sonarReading(2) < 30 then
			follow_avoid()
			fwd()
		elseif sonarReading(2) < 200 then
			turn(380, A)
			fwd()
		end
	until isPressed(ESCAPE)
end
wall()
